package com.nuoyuan.wx.wx.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nuoyuan.wx.common.controller.BaseController;
import com.nuoyuan.wx.common.dto.BaseRespDto;
import com.nuoyuan.wx.common.utils.DateUtil;
import com.nuoyuan.wx.common.utils.GsonUtil;
import com.nuoyuan.wx.common.utils.RedisUtil;
import com.nuoyuan.wx.dao.mapper.BookMapper;
import com.nuoyuan.wx.dao.po.BookPo;
import com.nuoyuan.wx.dao.po.UserPo;
import com.nuoyuan.wx.service.ProductService;
import com.nuoyuan.wx.vo.BookVo;
import com.nuoyuan.wx.vo.ProductVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;

/**
 * @Package com.nuoyuan.wx.wx.controller
 * @ClassName BookController
 * @Description TODO
 * @Author linus
 * @Date 2020-02-21 16:46
 * @Version 1.0
 **/
@RestController
public class BookController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(BookController.class);
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private ProductService productService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 预约
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wx/book", method = RequestMethod.POST)
    @ResponseBody
    public String book(@RequestBody BookPo param, HttpServletRequest request, HttpServletResponse response) {
        //token to user
        UserPo user = GsonUtil.fromJson(redisUtil.get(getToken(request)).toString(), UserPo.class);
        //get product info
        ProductVo productVo = new ProductVo();
        productVo.setProductId(param.getProductId());
        BaseRespDto<ProductVo> resp = productService.getDetail(productVo);
        if(!resp.isSuccess()) {
            log.error(resp.getMsg());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp(resp.getMsg());
        }

        if(param.getAppointmentAmount().compareTo(BigDecimal.ZERO) <= 0  ||
                param.getAppointmentAmount().compareTo(resp.getData().getStartAmount()) < 0 ||
                param.getAppointmentAmount().compareTo(resp.getData().getTotalCollection()) > 0) {
            log.error(resp.getMsg());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return this.buildErrorResp("投资金额异常或低于起投金额, 请重新输入。");
        }


        //save book
        Date current = DateUtil.getCurrentTimestamp();
        param.setCreateTime(current);
        param.setUpdateTime(current);
        param.setIdNo(user.getIdNo());
        param.setPhone(user.getPhone());
        param.setProductId(resp.getData().getProductId());
        param.setProductName(resp.getData().getProductName());
        param.setProductNo(resp.getData().getProductNo());
        param.setRealName(user.getRealName());
        param.setUserId(user.getUserId());
        param.setStartAmount(resp.getData().getStartAmount());
        param.setExpireationMonth(resp.getData().getExpireationMonth());
        param.setAnnualYield(resp.getData().getAnnualYield());
        bookMapper.insert(param);

        return this.buildSimpleSuccResp();
    }


    /**
     * 转让
     * @param param
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/wx/transfer", method = RequestMethod.POST)
    @ResponseBody
    public String transfer(@RequestBody BookVo param, HttpServletRequest request, HttpServletResponse response) {
        //token to user
        UserPo user = GsonUtil.fromJson(redisUtil.get(getToken(request)).toString(), UserPo.class);
        //限制转让金额
        Wrapper<BookPo> queryWrapper = new QueryWrapper<>();
        ((QueryWrapper<BookPo>) queryWrapper).eq("product_id", param.getProductId()).eq("is_deleted", 0);
        List<BookPo> existBooks = bookMapper.selectList(queryWrapper);

        BigDecimal restAmount = BigDecimal.ZERO;
        if(!CollectionUtils.isEmpty(existBooks)) {
            BigDecimal sumApointmentAmout = BigDecimal.ZERO;
            BigDecimal tmpAmount = BigDecimal.ZERO;
            for(BookPo po : existBooks) {
                sumApointmentAmout = sumApointmentAmout.add(po.getAppointmentAmount());
            }

            tmpAmount = sumApointmentAmout.add(param.getAppointmentAmount());
            if(tmpAmount.compareTo(param.getBookAmount()) > 0) {
                log.error("转让金额超过总金额, 请重新输入");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

                restAmount = param.getBookAmount().subtract(sumApointmentAmout);
                DecimalFormat decimalFormat =new DecimalFormat("#.00");
                return this.buildErrorResp("转让金额超过总金额, 剩余转让金额" + decimalFormat.format(restAmount) + "万元, 请重新输入。");
            }
        }else {
            if(param.getAppointmentAmount().compareTo(param.getBookAmount()) > 0) {
                log.error("转让金额超过总金额, 请重新输入");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                DecimalFormat decimalFormat =new DecimalFormat("#.00");
                return this.buildErrorResp("转让金额超过总金额, 剩余转让金额" + decimalFormat.format(param.getBookAmount()) + "万元, 请重新输入。");
            }
        }
        //save book
        Date current = DateUtil.getCurrentTimestamp();
        BookPo po = new BookPo();
        po.setCreateTime(current);
        po.setUpdateTime(current);
        po.setIdNo(user.getIdNo());
        po.setPhone(user.getPhone());
        po.setRealName(user.getRealName());
        po.setUserId(user.getUserId());
        po.setStartAmount(BigDecimal.ZERO);
        po.setProductName(param.getProductName());
        po.setProductNo(param.getProductNo());
        po.setProductId(param.getProductId());
        po.setAppointmentAmount(param.getAppointmentAmount());
        po.setAnnualYield(param.getAnnualYield());
        po.setBookType(param.getBookType());
        bookMapper.insert(po);
        return this.buildSimpleSuccResp();
    }

}
